package com.revai.engine.basic.service.impl;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import com.revai.engine.basic.core.AuditStateEnum;
import com.revai.engine.basic.service.ClassCacheService;
import com.revai.engine.basic.service.ReflectService;
import com.revai.engine.basic.service.TableService;
import com.revai.engine.basic.util.ExampleCriteria;
import com.revai.engine.basic.util.StrUtils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;

@Service
public class ReflectServiceImpl implements ReflectService {

    private final Logger logger = LoggerFactory.getLogger(ReflectServiceImpl.class);

    private static final String APPROVAL_STATUS = "approvalStatus";
    private static final String CREATED_BY = "createdBy";
    private static final String UPDATED_BY = "updatedBy";


    @Autowired
    private ApplicationContext applicationContext;

    @Lazy
    @Autowired
    private TableService tableService;

    @Autowired
    private Environment environment;

    @Autowired
    private ClassCacheService classCache;

    /**
     * 反射执行查询
     */
    @Override
    public List<Map<String, Object>> query(String tableName, JSONObject query) throws Exception {
        //获取小驼峰表名
        String modelName = StrUtils.toClassCamelCase(tableName);
        // 是否有历史表
        Boolean isHistory = false;
        // 判断是否是历史表,从HashMap看有没有
        // 有没有history关键字，有则true
        Object objHistory = query.get("history");
        // 如何是历史表
        if (objHistory != null && objHistory instanceof Boolean && (Boolean) objHistory) {
            isHistory = true;
            // tableName = tableName + "History";
            // modelName = modelName + "History";
        }
        // 创建Example查询
        ExampleCriteria example = new ExampleCriteria(modelName, classCache);
        // 增加条件approvalStatus!=-1删除状态
        if (isHistory) {
            // example.andNotEqualTo("approvalStatus", AuditStateEnum.DELETED.getCode());
        }
        // 查询条件
        if (query != null) {

            JSONArray ids = query.getJSONArray("ids");
            List<Long> queryIds = new ArrayList<>();

            if (ids != null && ids.size() > 0) {
                for (int i = 0; i < ids.size(); i++) {
                    queryIds.add(ids.getLong(i));
                }
                example.andIn("id", queryIds);
                query.remove("ids");
            }
            Set<String> keys = query.keySet();
            for (String key : keys) {
                String typeName = example.getFieldTypeName(key);
                if ("java.lang.Long".equals(typeName)) {
                    if (query.get(key) instanceof List) {
                        // 数字id查询，使用范围
                        JSONArray array = query.getJSONArray(key);
                        Long start = array.getLong(0);
                        Long end = array.getLong(1);
                        if (start != null && end != null) {
                            example.andBetween(key, start, end);
                        } else if (start != null) {
                            example.andGreaterThanOrEqualTo(key, start);
                        } else if (end != null) {
                            example.andLessThanOrEqualTo(key, end);
                        }
                    } else {
                        // 查询相等方法
                        example.andEqualTo(key, query.getLong(key));
                    }
                } else if ("java.lang.Integer".equals(typeName)) {
                    if (query.get(key) instanceof List) {
                        // 数字id查询，使用范围
                        JSONArray array = query.getJSONArray(key);
                        Integer start = array.getInt(0);
                        Integer end = array.getInt(1);
                        if (start != null && end != null) {
                            example.andBetween(key, start, end);
                        } else if (start != null) {
                            example.andGreaterThanOrEqualTo(key, start);
                        } else if (end != null) {
                            example.andLessThanOrEqualTo(key, end);
                        }
                    } else {
                        // 查询相等方法
                        example.andEqualTo(key, query.getInt(key));
                    }
                } else if ("java.util.Date".equals(typeName)) {
                    if (query.getStr(key, "").startsWith("[")) {
                        // 日期查询，使用范围
                        JSONArray array = query.getJSONArray(key);
                        Date start = array.getDate(0);
                        Date end = array.getDate(1);
                        if (start != null && end != null) {
                            example.andBetween(key, start, end);
                        } else if (start != null) {
                            example.andGreaterThanOrEqualTo(key, start);
                        } else if (end != null) {
                            example.andLessThanOrEqualTo(key, end);
                        }
                    } else {
                        Date date = query.getDate(key);
                        DateTime begin = DateUtil.beginOfDay(date);
                        DateTime end = DateUtil.endOfDay(date);
                        example.andBetween(key, begin.toJdkDate(), end.toJdkDate());
                    }

                } else if ("java.lang.String".equals(typeName)) {
                    String value = query.getStr(key);
                    if (value.contains(",")) {
                        example.andIn(key, Arrays.asList(value.split(",")));
                    } else {
                        // 字符串，全部使用like查询
                        example.andLike(key, "%" + query.getStr(key) + "%");                       
                    }
                    
                } else if ("java.lang.Boolean".equals(typeName)) {
                    example.andEqualTo(key, query.getBool(key));
                }  
                else {
                    // 查询相等方法
                    example.andEqualTo(key, query.getStr(key));
                }
            }
        }
        return convertResult(example.selectByExample());
    }

    /**
     * 反射执行新增
     */
    @Override
    public Long add(String tableName, JSONObject form)
            throws Exception {
        // // 获取当前认证对象
        // Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // // 获取 UserDetails 对象
        // UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        // // 获取用户名
        // String username = userDetails.getUsername();
        String username = "hujing";
        String modelName = StrUtils.toClassCamelCase(tableName);
        // logger.info(modelName);

        Class<?> modelClass = classCache.getModelClass(tableName);
        Class<?> mapperClass = classCache.getMapperClass(tableName);
        // 获取mapper
        Object bean = applicationContext.getBean(mapperClass);
        // 获取mapper的新增方法
        Method insertMethod = mapperClass.getMethod("insertSelective", modelClass);
        if (ReflectUtil.hasField(modelClass, APPROVAL_STATUS)) {
            form.put("approvalStatus", AuditStateEnum.PENDING.getCode());
        }
        if (ReflectUtil.hasField(modelClass, CREATED_BY)) {
            form.put("createdBy", username);
        }
        if (ReflectUtil.hasField(modelClass, UPDATED_BY)) {
            form.put("updatedBy", username);
        }
        // form
        Object modelValue = form.toBean(modelClass);
        // 执行新增方法
        // logger.info("insert to db");
        insertMethod.invoke(bean, modelValue);
        
        // 获取新增后的主键id
        Method getIdMethod = modelClass.getMethod("getId");
        // logger.info("getIdMethod");

        // 主键id
        Object dataId = getIdMethod.invoke(modelValue);
        return convertResult(dataId);
    }

    /**
     * 根据id查询记录
     * 
     * @param tableName
     * @param id
     * @return
     */
    @Override
    public Object getItem(String tableName, Long id) throws Exception {
        Class<?> mapperClass = classCache.getMapperClass(tableName);
        // 获取mapper
        Object bean = applicationContext.getBean(mapperClass);
        // 获取mapper的新增方法
        Method selectItemMethod = mapperClass.getMethod("selectByPrimaryKey", Long.class);
        return selectItemMethod.invoke(bean, id);
    }

    /**
     * 根据dataId从历史表查询一条记录，并转换成主表Model
     * 
     * @param tableName
     * @param id
     */
    @Override
    public Object getHistoryByDataId(String tableName, Long id) throws Exception {
        String historyTableName = tableName + "History";
        Class<?> modelClass = classCache.getModelClass(tableName);
        Class<?> historyMapperClass = classCache.getMapperClass(historyTableName);
        // 获取mapper
        Object historyBean = applicationContext.getBean(historyMapperClass);

        ExampleCriteria exampleCriteria = new ExampleCriteria(historyTableName, classCache);
        exampleCriteria.andEqualTo("dataId", id);
        exampleCriteria.andEqualTo("dataStatus", 1);
        // 查询历史记录
        List<Object> results = ReflectUtil.invoke(historyBean, "selectByExample", exampleCriteria.getExample());
        Object historyData = results.get(0);
        if (historyData == null) {
            return null;
        }
        JSONObject mainObject = new JSONObject(historyData);
        mainObject.put("id", id);
        return mainObject.toBean(modelClass);
    }

    /**
     * 根据ids查询列表数据
     * 
     * @param tableName
     * @param ids
     */
    @Override
    public List<Object> queryByIds(String tableName, List<Long> ids) throws Exception {
        Class<?> mapperClass = classCache.getMapperClass(tableName);
        // 获取mapper
        Object mapperBean = applicationContext.getBean(mapperClass);

        ExampleCriteria exampleCriteria = new ExampleCriteria(tableName, classCache);
        exampleCriteria.andIn("id", ids);
        List<Object> results = ReflectUtil.invoke(mapperBean, "selectByExample", exampleCriteria.getExample());
        return results;
    }

    /**
     * 反射执行更新
     */
    @Override
    public Integer update(String tableName, JSONObject form)
            throws Exception {
        // // 获取当前认证对象
        // Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // // 获取 UserDetails 对象
        // UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        // // 获取用户名
        // String username = userDetails.getUsername();
        String username = "hujing";

        Class<?> modelClass = classCache.getModelClass(tableName);
        Object sourceData = getItem(tableName, form.getLong("id"));
        if (sourceData == null) {
            throw new Exception("数据不存在");
        }
        Long dataId = ReflectUtil.invoke(sourceData, "getId");
        Integer approvalStatus = 0;
        if (ReflectUtil.hasField(modelClass, APPROVAL_STATUS)) {
            Object aStatus = ReflectUtil.invoke(sourceData, getGetter("approvalStatus"));
            if (aStatus != null) {
                approvalStatus = (Integer) aStatus;
            }
        }
        // 审批中，不允许修改
        if (approvalStatus.equals(AuditStateEnum.IN_APPROVAL.getCode())) {
            throw new Exception("审批中，不允许修改");
        }
        String historyTableName = "tableName";
        // 是否有历史表
        Boolean isHistory = false;
        // 判断是否是历史表
        Object objHistory = form.get("history");
        // 如果是历史表
        if (objHistory != null && objHistory instanceof Boolean && (Boolean) objHistory) {
            isHistory = true;
            historyTableName = tableName + "History";
        }

        // 有历史表根据审批状态approvalStatus，审批通过的，在历史表创建一条新记录，更新历史dataStatus=0，dataStatus=1是最后一条记录
        if (isHistory && approvalStatus.equals(AuditStateEnum.COMPLETED.getCode())) {
            Class<?> historyMapperClass = classCache.getMapperClass(historyTableName);
            Class<?> historyModelClass = classCache.getModelClass(historyTableName);
            Class<?> historyExampleClass = classCache.getExampleClass(historyTableName);
            // 获取mapper
            Object bean = applicationContext.getBean(historyMapperClass);
            // 获取id，将dataStatus更改成0历史
            ExampleCriteria exampleCriteria = new ExampleCriteria(historyTableName, classCache);
            exampleCriteria.andEqualTo("dataId", dataId);
            JSONObject updateObj = new JSONObject();
            updateObj.put("dataStatus", 0);
            Object updateBean = updateObj.toBean(historyModelClass);
            Method updateByPrimaryKeyMethod = historyMapperClass.getMethod("updateByExampleSelective",
                    historyModelClass, historyExampleClass);
            ReflectUtil.invoke(bean, updateByPrimaryKeyMethod, updateBean, exampleCriteria.getExample());
            // 审批通过的在历史表插入一条数据
            JSONObject insertObject = new JSONObject(sourceData);
            insertObject.put("dataId", dataId);
            insertObject.put("dataStatus", 1);
            JSONObject insertData = StrUtils.MergeJSONObjects(insertObject, form);
            Object historyData = insertData.toBean(historyModelClass);
            // 插入新数据
            Method insertMethod = historyMapperClass.getMethod("insertSelective", historyModelClass);
            // 将form合并入result后插入
            insertMethod.invoke(bean, historyData);
            return 1;
        } else {
            // Class<?> modelClass = classCache.getModelClass(tableName);
            Class<?> mapperClass = classCache.getMapperClass(tableName);
            // 获取mapper
            Object bean = applicationContext.getBean(mapperClass);
            // 获取mapper的更新方法
            Method updateMethod = mapperClass.getMethod("updateByPrimaryKeySelective", modelClass);
            if (ReflectUtil.hasField(modelClass, UPDATED_BY)) {
                form.put("updatedBy", username);
            }
            // form
            Object modelValue = form.toBean(modelClass);
            Object result = updateMethod.invoke(bean, modelValue);
            return convertResult(result);
        }
    }

    /**
     * 反射执行提交审批
     */
    @Override
    public Integer audit(String tableName, JSONObject form, String authToken)
            throws Exception {
        // 创建历史记录，更新状态
        createHistory(tableName, form, "");
        Long businessId = form.getLong("id");
        // 判断是否是历史表
        // 配置有processKey，发起流程审批
        Object processKey = form.get("processKey");
        if (processKey != null) {
            JSONObject reqJson = new JSONObject();
            reqJson.put("processKey", processKey);
            reqJson.put("businessId", businessId);
            LocalDateTime cutoffTime = LocalDateTime.now().plusDays(7L);
            reqJson.put("cutoffTime", cutoffTime);
            // 开发环境调用接口
            // if (isDevelopment()) {
            //     ServiceUtil.doHttp("/wfCommonProcess/v1/startWorkflow", reqJson, authToken);
            // } else {
            //     ProcessStartDTO processStartDTO = new ProcessStartDTO().setProcessKey((String) processKey)
            //             .setBusinessId(businessId)
            //             .setSource("vmrs-app")
            //             .setCutoffTime(cutoffTime);
            //     feignClient.startWorkflow(processStartDTO);
            // }
        }
        return 1;
    }

    /**
     * 反射执行审批
     */
    @Override
    public Integer approve(String tableName, JSONObject form, String authToken)
            throws Exception {
        // 执行审批
        // if (isDevelopment()) {
        //     ServiceUtil.doHttp("/wfCommonProcess/v1/processApproval", form, authToken);
        // } else {
        //     ProcessApprovalDTO processApprovalDTO = form.toBean(ProcessApprovalDTO.class);
        //     feignClient.processApproval(processApprovalDTO);
        // }
        // 审批通过后，更新状态
        Long businessId = form.getLong("wpBusinessId");
        // 更新历史记录和主表
        approveHistory(tableName, businessId);
        return 1;
    }

    /**
     * 反射执行删除
     */
    @Override
    public Integer delete(String tableName, Long id)
            throws Exception {
        Class<?> mapperClass = classCache.getMapperClass(tableName);
        // 获取mapper
        Object bean = applicationContext.getBean(mapperClass);
        // 获取mapper的删除方法
        Method deleteMethod = mapperClass.getMethod("deleteByPrimaryKey", Long.class);
        // form
        Object result = deleteMethod.invoke(bean, id);
        return convertResult(result);
    }

    /**
     * 提交审批时，单表创建历史记录
     * @param tableName
     * @param form
     * @return
     * @throws Exception
     */
    
    @Override
    public Long createHistory(String tableName, JSONObject form, String processKey) throws Exception {
        // 获取当前认证对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        // 获取登录用户名
        String username = userDetails.getUsername();
        // 主表model
        String modelName = StrUtils.toClassCamelCase(tableName);
        Class<?> modelClass = classCache.getModelClass(tableName);
        // 根据id查询主表记录
        Object sourceData = getItem(modelName, form.getLong("id"));
        if (sourceData == null) {
            throw new Exception("数据不存在");
        }
        // 数据主键id
        Long businessId = ReflectUtil.invoke(sourceData, "getId");
        Integer approvalStatus = 0;
        // 获取审批状态
        // if (ReflectUtil.hasField(modelClass, "approvalStatus")) {
        //     Object aStatus = ReflectUtil.invoke(sourceData, getGetter("approvalStatus"));
        //     if (aStatus != null) {
        //         approvalStatus = (Integer) aStatus;
        //     }
        // }
        // 审批中，不允许修改
        if (approvalStatus.equals(AuditStateEnum.IN_APPROVAL.getCode())) {
            throw new Exception("审批中，不允许修改");
        }
        // 是否有历史表
        Boolean isHistory = false;
        String historyTableName = tableName;
        // 判断是否是历史表
        Object objHistory = form.get("history");
        // 如果是历史表
        if (objHistory != null && objHistory instanceof Boolean && (Boolean) objHistory) {
            isHistory = true;
            historyTableName = modelName + "History";
        }
        // 更新审批状态为审批中，历史表新增记录，修改已有历史表数据
        // merge主表和提交的数据
        JSONObject insertObject = new JSONObject(sourceData);
        JSONObject insertData = StrUtils.MergeJSONObjects(insertObject, form);
        Class<?> mapperClass = classCache.getMapperClass(tableName);
        // 获取mapper的更新方法
        Method updateMethod = mapperClass.getMethod("updateByPrimaryKeySelective", modelClass);
        Object bean = applicationContext.getBean(mapperClass);
        // 如果是待提交状态，先更新主表
        if (approvalStatus.equals(AuditStateEnum.PENDING.getCode())) {
            // 将提交的form更新主表数据
            // 获取mapper
            if (ReflectUtil.hasField(modelClass, UPDATED_BY)) {
                insertData.put("updatedBy", username);
            }
            // if (ReflectUtil.hasField(modelClass, "updatedAt")) {
            //     insertData.put("updatedAt", new Date());
            // }
            if (ReflectUtil.hasField(modelClass, "configApprovalStatus") && processKey.equals("vmrs-warehouse-partnumber")) {
                insertData.put("configApprovalStatus", AuditStateEnum.IN_APPROVAL.getCode());
            } else if (ReflectUtil.hasField(modelClass, APPROVAL_STATUS)) {
                insertData.put("approvalStatus", AuditStateEnum.IN_APPROVAL.getCode());
            }
            // 更新主表
            Object modelValue = insertData.toBean(modelClass);
            updateMethod.invoke(bean, modelValue);
        } else {
            JSONObject updateMain = new JSONObject();
            updateMain.put("id", businessId);

            if (ReflectUtil.hasField(modelClass, "configApprovalStatus") && processKey.equals("vmrs-warehouse-partnumber")) {
                updateMain.put("configApprovalStatus", AuditStateEnum.IN_APPROVAL.getCode());
            } else if (ReflectUtil.hasField(modelClass, APPROVAL_STATUS)) {
                updateMain.put("approvalStatus", AuditStateEnum.IN_APPROVAL.getCode());
            }
            // 更新主表
            Object modelValue = updateMain.toBean(modelClass);
            updateMethod.invoke(bean, modelValue);
        }
        if (isHistory) {
            // 插入更新历史表
            Class<?> historyMapperClass = classCache.getMapperClass(historyTableName);
            Class<?> historyModelClass = classCache.getModelClass(historyTableName);
            Class<?> historyExampleClass = classCache.getExampleClass(historyTableName);
            // 获取mapper
            Object historyBean = applicationContext.getBean(historyMapperClass);
            // 根据dataId，将历史表dataStatus更改成0历史
            ExampleCriteria exampleCriteria = new ExampleCriteria(historyTableName, classCache);
            exampleCriteria.andEqualTo("dataId", businessId);
            exampleCriteria.andEqualTo("dataStatus", 1);
            JSONObject updateObj = new JSONObject();
            updateObj.put("dataStatus", 0);
            if (ReflectUtil.hasField(modelClass, UPDATED_BY)) {
                insertData.put("updatedBy", username);
            }
            Object updateBean = updateObj.toBean(historyModelClass);
            Method updateByPrimaryKeyMethod = historyMapperClass.getMethod("updateByExampleSelective",
                    historyModelClass, historyExampleClass);
            ReflectUtil.invoke(historyBean, updateByPrimaryKeyMethod, updateBean, exampleCriteria.getExample());
            // 在历史表插入一条数据
            if (ReflectUtil.hasField(modelClass, "configApprovalStatus")) {
                insertData.put("configApprovalStatus", AuditStateEnum.IN_APPROVAL.getCode());
            } else if (ReflectUtil.hasField(modelClass, APPROVAL_STATUS)) {
                insertData.put("approvalStatus", AuditStateEnum.IN_APPROVAL.getCode());
            }
            insertData.put("dataId", businessId);
            insertData.put("dataStatus", 1);
            insertData.remove("id");
            Object historyData = insertData.toBean(historyModelClass);
            // 插入新数据
            Method insertMethod = historyMapperClass.getMethod("insertSelective", historyModelClass);
            // 将form合并入result后插入
            insertMethod.invoke(historyBean, historyData);
            return ReflectUtil.invoke(historyData, "getId");
        } else {
            return 0L;
        }
    }

    public Integer auditAll(String tableName, JSONObject form, String authToken)
            throws Exception {
        // 获取当前认证对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 获取 UserDetails 对象
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        // 获取用户名
        String username = userDetails.getUsername();
        String modelName = StrUtils.toClassCamelCase(tableName);

        Class<?> modelClass = classCache.getModelClass(tableName);
        // 根据id查询记录
        Object sourceData = getItem(modelName, form.getLong("id"));
        if (sourceData == null) {
            throw new Exception("数据不存在");
        }
        // 数据主键id
        Long dataId = ReflectUtil.invoke(sourceData, "getId");
        Integer approvalStatus = 0;
        if (ReflectUtil.hasField(modelClass, APPROVAL_STATUS)) {
            Object aStatus = ReflectUtil.invoke(sourceData, getGetter("approvalStatus"));
            if (aStatus != null) {
                approvalStatus = (Integer) aStatus;
            }
        }
        // 审批中，不允许修改
        if (approvalStatus.equals(AuditStateEnum.IN_APPROVAL.getCode())) {
            throw new Exception("审批中，不允许修改");
        }
        // 是否有历史表
        Boolean isHistory = false;
        String historyTableName = tableName;
        // 判断是否是历史表
        Object objHistory = form.get("history");
        // 如果是历史表
        if (objHistory != null && objHistory instanceof Boolean && (Boolean) objHistory) {
            isHistory = true;
            historyTableName = tableName + "History";
        }
        // 更新审批状态为审批中，历史表新增记录，修改已有历史表数据
        if (isHistory) {
            // merge主表和提交的数据
            JSONObject insertObject = new JSONObject(sourceData);
            JSONObject insertData = StrUtils.MergeJSONObjects(insertObject, form);
            Class<?> mapperClass = classCache.getMapperClass(tableName);
            // 获取mapper的更新方法
            Method updateMethod = mapperClass.getMethod("updateByPrimaryKeySelective", modelClass);
            Object bean = applicationContext.getBean(mapperClass);
            // 如果是待提交状态，先更新主表
            if (approvalStatus.equals(AuditStateEnum.PENDING.getCode())) {
                // 将提交的form更新主表数据
                // 获取mapper
                if (ReflectUtil.hasField(modelClass, UPDATED_BY)) {
                    insertData.put("updatedBy", username);
                }
                // if (ReflectUtil.hasField(modelClass, "updatedAt")) {
                //     insertData.put("updatedAt", new Date());
                // }
                if (ReflectUtil.hasField(modelClass, APPROVAL_STATUS)) {
                    insertData.put("approvalStatus", AuditStateEnum.IN_APPROVAL.getCode());
                }
                // 更新主表
                Object modelValue = insertData.toBean(modelClass);
                updateMethod.invoke(bean, modelValue);
            } else {
                JSONObject updateMain = new JSONObject();
                updateMain.put("id", dataId);
                updateMain.put("approvalStatus", AuditStateEnum.IN_APPROVAL.getCode());
                // 更新主表
                Object modelValue = updateMain.toBean(modelClass);
                updateMethod.invoke(bean, modelValue);
            }
            // 插入更新历史表
            Class<?> historyMapperClass = classCache.getMapperClass(historyTableName);
            Class<?> historyModelClass = classCache.getModelClass(historyTableName);
            Class<?> historyExampleClass = classCache.getExampleClass(historyTableName);
            // 获取mapper
            Object historyBean = applicationContext.getBean(historyMapperClass);
            // 根据dataId，将历史表dataStatus更改成0历史
            ExampleCriteria exampleCriteria = new ExampleCriteria(historyTableName, classCache);
            exampleCriteria.andEqualTo("dataId", dataId);
            exampleCriteria.andEqualTo("dataStatus", 1);
            JSONObject updateObj = new JSONObject();
            updateObj.put("dataStatus", 0);
            if (ReflectUtil.hasField(modelClass, UPDATED_BY)) {
                insertData.put("updatedBy", username);
            }
            // if (ReflectUtil.hasField(modelClass, "updatedAt")) {
            //     insertData.put("updatedAt", new Date());
            // }
            Object updateBean = updateObj.toBean(historyModelClass);
            Method updateByPrimaryKeyMethod = historyMapperClass.getMethod("updateByExampleSelective",
                    historyModelClass, historyExampleClass);
            ReflectUtil.invoke(historyBean, updateByPrimaryKeyMethod, updateBean, exampleCriteria.getExample());
            // 在历史表插入一条数据
            insertData.put("dataId", dataId);
            insertData.put("dataStatus", 1);
            Object historyData = insertData.toBean(historyModelClass);
            // 插入新数据
            Method insertMethod = historyMapperClass.getMethod("insertSelective", historyModelClass);
            // 将form合并入result后插入
            insertMethod.invoke(historyBean, historyData);
            // 配置有processKey，发起流程审批
            Object processKey = form.get("processKey");
            if (processKey != null) {
                JSONObject reqJson = new JSONObject();
                reqJson.put("processKey", processKey);
                reqJson.put("businessId", dataId);
                LocalDateTime cutoffTime = LocalDateTime.now().plusDays(7L);
                reqJson.put("cutoffTime", cutoffTime);
                // 开发环境调用接口
                // if (isDevelopment()) {
                //     ServiceUtil.doHttp("/wfCommonProcess/v1/startWorkflow", reqJson, authToken);
                // } else {
                //     ProcessStartDTO processStartDTO = new ProcessStartDTO().setProcessKey((String) processKey)
                //             .setBusinessId(dataId)
                //             .setCutoffTime(cutoffTime);
                //     feignClient.startWorkflow(processStartDTO);
                // }
            }
            return 1;
        } else {
            return 0;
        }
    }
    /**
     * 审批通过时，单表更新历史记录和主表数据
     * @param tableName
     * @param businessId
     * @return
     * @throws Exception
     */
    @Override
    public Long approveHistory(String tableName, Long businessId) throws Exception {
        String modelName = StrUtils.toClassCamelCase(tableName);
        // 修改数据保存在历史表，将历史表数据update到主表
        String historyTableName = modelName + "History";
        Class<?> historyMapperClass = classCache.getMapperClass(historyTableName);
        // 获取mapper
        Object historyBean = applicationContext.getBean(historyMapperClass);
        Long historyId = 0L;
        // 获取历史表dataStatus=1的有效数据
        ExampleCriteria exampleCriteria = new ExampleCriteria(historyTableName, classCache);
        exampleCriteria.andEqualTo("dataId", businessId);
        exampleCriteria.andEqualTo("dataStatus", 1);
        List<Object> results = ReflectUtil.invoke(historyBean, "selectByExample", exampleCriteria.getExample());
        if (results != null && results.size() > 0 && results.get(0) != null) {
            Object updateData = results.get(0);
            // 将历史表数据update到主表，同时将主表审批状态改成审批通过
            JSONObject updateObject = new JSONObject(updateData);
            // 获取历史表id
            historyId = updateObject.getLong("id");
            updateObject.put("id", businessId);
            updateObject.put("approvalStatus", AuditStateEnum.COMPLETED.getCode());
            updateObject.put("configApprovalStatus", AuditStateEnum.COMPLETED.getCode());
            updateObject.put("dataStatus", 1);
            // updateObject.put("updatedAt", new Date());
            updateObject.remove("createdBy");
            updateObject.remove("createdAt");
            Class<?> modelClass = classCache.getModelClass(tableName);
            Class<?> mapperClass = classCache.getMapperClass(tableName);
            Object mapperBean = applicationContext.getBean(mapperClass);
            Object model = updateObject.toBean(modelClass);
            ReflectUtil.invoke(mapperBean, "updateByPrimaryKeySelective", model);

            // 更新历史表的审批状态
            Class<?> historyModelClass = classCache.getModelClass(historyTableName);
            Class<?> historyExampleClass = classCache.getExampleClass(historyTableName);
            // 根据dataId，将历史表dataStatus更改成0历史
            JSONObject updateObj = new JSONObject();
            updateObj.put("approvalStatus", AuditStateEnum.COMPLETED.getCode());
            // updateObj.put("updatedAt", new Date());
            updateObj.put("dataStatus", 1);

            Object updateBean = updateObj.toBean(historyModelClass);
            Method updateByExampleMethod = historyMapperClass.getMethod("updateByExampleSelective",
                    historyModelClass, historyExampleClass);
            ReflectUtil.invoke(historyBean, updateByExampleMethod, updateBean, exampleCriteria.getExample());
        }
        return historyId;
    }

    /**
     * 类型转换
     * 
     * @param <T>
     * @param result
     * @return
     */
    @SuppressWarnings("unchecked")
    private static <T> T convertResult(Object result) {
        try {
            // 这里使用了强制类型转换，需要确保类型匹配
            return (T) result;
        } catch (ClassCastException e) {
            // 处理类型不匹配的情况
            e.printStackTrace();
            // 或者抛出异常，根据具体情况处理
            return null;
        }
    }

    /**
     * 根据字段key获取getter方法名
     * 
     * @param key
     * @return
     */
    private String getGetter(String key) {
        return "get" + key.substring(0, 1).toUpperCase() + key.substring(1);
    }

    // 检查是否是开发环境
    private boolean isDevelopment() {
        for (String profile : environment.getActiveProfiles()) {
            if ("dev".equalsIgnoreCase(profile)) {
                return true;
            }
        }
        return false;
    }
}
